console.log("用户管理系统已启动！");
let userData = [
    {
    id: 1,
    name: "张三",
    email: "zhangsan@example.com",
    phone: "13800138000",
    registerTime: "2025/09/01 10:30:00"
    },
    {
    id: 2,
    name: "李四",
    email: "lisi@example.com",
    phone: "13900139000",
    registerTime: "2025/09/02 14:15:00"
    }
    ];
    
    let gridInstance = null;
    let userIdCounter = 3; // 从3开始，避免与默认数据冲突
    
    // 更新用户总数显示函数
    function updateUsersCount() {
    document.getElementById('userCount').textContent = userData.length;
    document.getElementById('lastUpdateTime').textContent = new Date().toLocaleString();
    }
    function initGrid() {
        if (gridInstance) {
            gridInstance.destroy(); // 销毁旧实例（用于刷新时重建）
        }
    
        gridInstance = new gridjs.Grid({
            columns: [
                { name: '#', id: 'id', width: '8%' },
                { name: '姓名', id: 'name', width: '15%', sort: true },
                { name: '邮箱', id: 'email', width: '25%', sort: true },
                { name: '电话', id: 'phone', width: '15%', sort: true },
                { name: '注册时间', id: 'registerTime', width: '20%', sort: true },
                {
                    name: '操作',
                    id: 'actions',
                    width: '17%',
                    formatter: (cell, row) => {
                        return gridjs.h('div', { className: 'text-center' }, [
                            gridjs.h('button', {
                                className: 'btn btn-sm btn-outline-primary me-1 edit-btn',
                                title: '编辑',
                                onClick: () => handleEdit(row.cells[0].data) // 暂未实现
                            }, gridjs.h('i', { className: 'fas fa-edit' })),
                            gridjs.h('button', {
                                className: 'btn btn-sm btn-outline-danger delete-btn',
                                title: '删除',
                                onClick: () => handleDelete(row.cells[0].data)
                            }, gridjs.h('i', { className: 'fas fa-trash' }))
                        ]);
                    }
                }
            ],
            data: userData,
            pagination: {
                enabled: true,
                limit: 5 // 每页5条
            },
            search: true, // 启用搜索
            sort: true, // 启用排序
            language: {
                search: {
                    placeholder: '搜索用户 … '
                },
                pagination: {
                    previous: '上一页',
                    next: '下一页',
                    showing: '显示第',
                    of: '条，共',
                    to: '至',
                    results: '条记录'
                }
            }
        }).render(document.getElementById("gridjs-container"));
    }
    document.addEventListener('DOMContentLoaded', function() {
        initGrid();
        updateUsersCount();
        bindEventListeners(); // 绑定按钮事件（下一步实现）
    });
    document.addEventListener('DOMContentLoaded', function() {
    initGrid();
    updateUsersCount();
    bindEventListeners(); // 绑定按钮事件（下一步实现）
});
function bindEventListeners() {
    const addUserBtn = document.getElementById('btnAddUser');
    const refreshBtn = document.getElementById('btnRefresh');

    // 添加用户按钮点击事件
    addUserBtn.addEventListener('click', function() {
        const newUser = {
            id: userIdCounter,
            name: '新用户' + userIdCounter,
            email: 'newuser' + userIdCounter + '@example.com',
            phone: '1380013808' + (userIdCounter % 10),
            registerTime: new Date().toLocaleString()
            
        };

        userData.push(newUser); // 添加到数据数组
        userIdCounter++;

        initGrid(); // 重新渲染表格
        updateUsersCount();

        Toastify({
            text: "成功添加新用户",
            duration: 3000,
            close: true,
            backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
            style: {
                borderRadius: "10px"
            }
        }).showToast();
    });

    // 刷新数据按钮点击事件
    refreshBtn.addEventListener('click', function() {
        // 重置数据
        userData = [
            {
                id: 1,
                name: "张三",
                email: "zhangsan@example.com",
                phone: "13800138000",
                registerTime: "2025-09-01 10:30:00"
            },
            {
                id: 2,
                name: "李四",
                email: "lisi@example.com",
                phone: "13980139000",
                registerTime: "2025-09-02 14:15:00"
               
            }
        ];
        userIdCounter = 3;

        initGrid();
        updateUsersCount();

        Toastify({
            text: "用户数据已刷新",
            duration: 3000,
            close: true,
            backgroundColor: "linear-gradient(to right, #1e3c72, #2a5298)",
            style: {
                borderRadius: "10px"
            }
        }).showToast();
    });
}
function handleDelete(userId) {
    if (confirm(`确定要删除 ID 为 ${userId} 的用户吗？`)) {
        userData = userData.filter(user => user.id !== userId);
        initGrid();
        updateUsersCount();

        Toastify({
            text: "用户删除成功",
            duration: 3000,
            close: true,
            backgroundColor: "linear-gradient(to right, #ff5f6d, #ffc371)",
            style: {
                borderRadius: "10px"
            }
        }).showToast();
    }
}
function handleEdit(userId) {
    const user = userData.find(u => u.id === userId);
    if (user) {
        Toastify({
            text: `编辑用户：${user.name}（ID: ${userId}）(功能待实现)`,
            duration: 3000,
            close: true,
            gravity: "top",
            position: "right",
            backgroundColor: "linear-gradient(to right, #667eea, #764ba2)",
            style: {
                borderRadius: "10px"
            }
        }).showToast();
    }
}
